package com.bbjob.controller.client;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.bbjob.client.dataentity.ResultForDeliveryClientLoginLog;
import com.bbjob.dto.Result;
import com.bbjob.mapper.DeliveryQuestionBankMapper;
import com.bbjob.mapper.DeliveryVersionUpgradeMapper;
import com.bbjob.model.CenterMacSignin;
import com.bbjob.model.DeliveryExamineeInfo;
import com.bbjob.model.DeliveryQuestionBank;
import com.bbjob.model.DeliveryVersionUpgrade;
import com.bbjob.service.IClientService;
import com.bbjob.service.ISystemService;

@Api(tags = "clientApi", description = "客户端接口")
@RestController
@RequestMapping(path = "client", produces = "application/json;charset=utf-8")
public class ClientSystemController {
	
	@Resource
	private IClientService clientService;
	
	@Resource
	private DeliveryQuestionBankMapper deliveryQuestionBankMapper;
	
	@Resource
	private DeliveryVersionUpgradeMapper deliveryVersionUpgradeMapper;
	
	@Resource
	private ISystemService systemService;
	
	@Value("${sys.local.exam.paper.path}")
	private String paperPath;
	@Value("${sys.local.client.path}")
	private String clientPath;
	
	@ApiOperation(value="考生登录", notes="考生登录")
	@ApiImplicitParam(name="examineeInfo", value="考生信息", required=true, dataType="DeliveryExamineeInfo")
	@RequestMapping(value="login", method=RequestMethod.POST)
	public ResultForDeliveryClientLoginLog entryExaminee(@RequestBody DeliveryExamineeInfo examineeInfo, HttpServletRequest request) {
		
		return clientService.dologin(examineeInfo, request);
	}
	
	@ApiOperation(value="试题下载", notes="试题下载")
	@RequestMapping(value="getPaper/{eId}/{qId}", method=RequestMethod.GET)
	public String downloadPaper(@PathVariable("eId") String eId, @PathVariable("qId") String qId, HttpServletResponse response) throws Exception {
		
		DeliveryQuestionBank bank = deliveryQuestionBankMapper.selectByPrimaryKey(qId);
		
		if (bank != null) {
			String filePath = paperPath + "/" + eId + "/" + qId + "/"; 
			String fileName="";
			
			if (bank.getPackageUrl() != null && !"".equals(bank.getPackageUrl())) {
				fileName = bank.getPackageUrl();
			}
			
			File file = new File(filePath , fileName);
		     
			if (file.exists()) {
				response.setContentType("application/octet-stream");// 
				response.setHeader("content-type", "application/octet-stream");
	            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"),"iso-8859-1"));// 设置文件名
	            byte[] buffer = new byte[1024];
	            FileInputStream fis = null;
	            BufferedInputStream bis = null;
	            try {
	                fis = new FileInputStream(file);
	                bis = new BufferedInputStream(fis);
	                OutputStream os = response.getOutputStream();
	                int i = bis.read(buffer);
	                while (i != -1) {
	                    os.write(buffer, 0, i);
	                    i = bis.read(buffer);
	                }
	                System.out.println("success");
	            } catch (Exception e) {
	                e.printStackTrace();
	            } finally {
	            	if (bis != null) {
	            		try {
	            			bis.close();
	            		} catch (IOException e) {
	            			e.printStackTrace();
	            		}
	            	}
	            	if (fis != null) {
	            		try {
	            			fis.close();
	            		} catch (IOException e) {
	            			e.printStackTrace();
	            		}
	            	}
	             }
	         }
		}
		
		return null;
	}
	
	@ApiOperation(value="考试机注册", notes="考试机注册")
	@ApiImplicitParam(name="centerMacSignin", value="考试机信息", required=true, dataType="CenterMacSignin")
	@RequestMapping(value="registe", method=RequestMethod.POST)
	public Result registe(@RequestBody CenterMacSignin centerMacSignin, HttpServletRequest request) {
		
		return systemService.registe(centerMacSignin, request);
	}
	
	@ApiOperation(value="考试机是否注册", notes="考试机是否注册")
	@ApiImplicitParam(name="centerMacSignin", value="考试机信息", required=true, dataType="CenterMacSignin")
	@RequestMapping(value="isRegiste", method=RequestMethod.POST)
	public Result isRegiste(@RequestBody CenterMacSignin centerMacSignin, HttpServletRequest request) {
		
		return systemService.isRegiste(centerMacSignin, request);
	}
	
	@ApiOperation(value="获取组织信息", notes="获取组织信息")
	@RequestMapping(value="getOrganInfo", method=RequestMethod.GET)
	public Result getOrganInfo() {
		
		return new Result(systemService.getOrganInfo().getData());
	}
	
	@ApiOperation(value="查看升级(考试端)", notes="查看升级")
	@RequestMapping(value="checkUpgradeForExam", method=RequestMethod.GET)
	public Result checkUpgradeForExam() {
		return new Result(systemService.selectUpdateInfo());
	}
	
	@ApiOperation(value="考试机更新包下载", notes="考试机更新包下载")
	@RequestMapping(value="getClient/{id}", method=RequestMethod.GET)
	public String downloadClient(@PathVariable("id") Integer id, HttpServletResponse response) throws Exception {
		
		DeliveryVersionUpgrade version = deliveryVersionUpgradeMapper.selectByPrimaryKey(id);
		
		if (version != null) {
			String filePath = clientPath + "/" + version.getVersionNo(); 
			String fileName="";
			if (version.getFilePath() != null && !"".equals(version.getFilePath())) {
				fileName = version.getFilePath();
			}
			
			File file = new File(filePath , fileName);
		     
			if (file.exists()) {
				response.setContentType("application/octet-stream");// 
				response.setHeader("content-type", "application/octet-stream");
	            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"),"iso-8859-1"));// 设置文件名
	            byte[] buffer = new byte[1024];
	            FileInputStream fis = null;
	            BufferedInputStream bis = null;
	            try {
	                fis = new FileInputStream(file);
	                bis = new BufferedInputStream(fis);
	                OutputStream os = response.getOutputStream();
	                int i = bis.read(buffer);
	                while (i != -1) {
	                    os.write(buffer, 0, i);
	                    i = bis.read(buffer);
	                }
	                System.out.println("success");
	            } catch (Exception e) {
	                e.printStackTrace();
	            } finally {
	            	if (bis != null) {
	            		try {
	            			bis.close();
	            		} catch (IOException e) {
	            			e.printStackTrace();
	            		}
	            	}
	            	if (fis != null) {
	            		try {
	            			fis.close();
	            		} catch (IOException e) {
	            			e.printStackTrace();
	            		}
	            	}
	             }
	         }
		} 
		
		return null;
	}
	
}
